#include <iostream>
#include "Wrappers/Pthread/Mutex.hpp"
#include "Wrappers/Pthread/ThreadException.hpp"

namespace wrappers {
namespace pthread {

Mutex::Mutex() {
  if (pthread_mutex_init(&mMutex, 0) != 0)
    throw pthread::ThreadException("Mutex: failed to initialize the mutex");
  mState = FREE;
}

Mutex::~Mutex() {
  pthread_mutex_destroy(&mMutex);
}

void Mutex::Lock() {
  if (pthread_mutex_lock(&mMutex) != 0)
    throw pthread::ThreadException("Mutex: failed to lock the mutex");
  mState = LOCKED;
}

bool Mutex::TryLock() {
  return (pthread_mutex_trylock(&mMutex) == 0);
}

void Mutex::Unlock() {
  if (pthread_mutex_unlock(&mMutex) != 0)
    throw pthread::ThreadException("Mutex: failed to unlock the mutex");
  mState = FREE;
}

Mutex::eState Mutex::GetState() const {
  return mState;
}

pthread_mutex_t &Mutex::GetMutex() {
  return mMutex;
}

}
}
